package org.example.chat.api;

import com.mybatisflex.core.query.QueryWrapper;
import org.example.chat.entity.ChatUserEntity;
import org.example.chat.mapper.ChatUserMapper;
import org.example.common.api.UserInterface;
import org.example.common.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.common.api.UserInterface;

import java.security.Timestamp;
import java.util.Date;

@Service("chatUserService")
public class UserService {
    @Autowired
    private UserInterface userInterface;

    @Autowired
    ChatUserMapper chatUserMapper;

   public void saveChatUser(Long userId){
       SysUser sysUser = userInterface.getSysUser(userId);

       QueryWrapper queryWrapper = QueryWrapper.create()
               .eq(ChatUserEntity::getPhone, sysUser.getMobile());

       ChatUserEntity chatUserEntity = chatUserMapper.selectOneByQuery(queryWrapper);
       if (chatUserEntity == null) {
            chatUserEntity = new ChatUserEntity();

           chatUserEntity.setUserId(sysUser.getUserId());
           chatUserEntity.setUsername(sysUser.getUsername());
           chatUserEntity.setPassword(sysUser.getPassword());
           chatUserEntity.setAvatar("https://randomuser.me/api/portraits/men/3.jpg");
           chatUserEntity.setEmail(sysUser.getEmail());
           chatUserEntity.setPhone(sysUser.getMobile());
           chatUserEntity.setStatus(1);
           chatUserEntity.setCreatedAt(new Date());
           chatUserEntity.setUpdatedAt(new Date());
           chatUserEntity.setMuted(0);
           chatUserEntity.setLastActive(new Date());
           chatUserMapper.insert(chatUserEntity);
       }else{
           chatUserEntity.setUsername(sysUser.getUsername());
           chatUserEntity.setEmail(sysUser.getEmail());
           chatUserEntity.setPhone(sysUser.getMobile());
           chatUserEntity.setUpdatedAt(new Date());
           chatUserEntity.setLastActive(new Date());
           chatUserMapper.update(chatUserEntity);
       }

   }
}
